package no.sogl.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

public class SoglUtils {
    private static final String SINGLE_MAIL_PATTERN = "(?mis)[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}";
    private static final Pattern MAIL_PATTERN = Pattern.compile(SINGLE_MAIL_PATTERN);
    private static final String MOBILE_REGEX = "^(4|5|9)\\d{7}";

    private SoglUtils() {
        // static helper class
    }

    public static List<String> mailRecipientsAsList(String recipients) {
        Matcher matcher = MAIL_PATTERN.matcher(recipients);
        List<String> addresses = new ArrayList<String>();
        while (matcher.find())
            addresses.add(matcher.group());
        return addresses;
    }
    
    public static final boolean isMobile(String phone){
        if ( !StringUtils.hasText(phone)) return false;
        return phone.matches(MOBILE_REGEX);
    }

    public static List<String> phonesAsList(String phones) {
        String phone = phones.replaceAll("[\r\n/]+", ",").replaceAll("\\s+", "");
        Matcher matcher = Pattern.compile("(?mis)\\d{8}").matcher(phone);
        List<String> addresses = new ArrayList<String>();
        while (matcher.find())
            addresses.add(matcher.group());
        
        if (CollectionUtils.isEmpty(addresses)) addresses.add(phone);
        Collections.sort(addresses, new Comparator<String>() {
            public int compare(String o1, String o2) {
                if ( o1 == o2) return 0;
                if ( o1 == null ) return 1;
                if ( o2 == null) return -1;
                if ( isMobile(o1) == isMobile(o2)) return 0;
                if ( isMobile(o1)) return -1;
                return 1;
            }
        });
        return addresses;
    }
}
